package com.yunc.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.yunc.common.httpclient.HttpClientService;
import com.yunc.common.httpclient.HttpResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author taocongcong
 * @create 2018-11-21 14:44
 */
public class AddressUtils {

    private static final Logger logger = LogManager.getLogger(AddressUtils.class);
    private static final HttpClientService httpClientService = (HttpClientService)SpringContextUtils.getBean("httpClientService");

    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        // 内网不查询
        if (IPUtils.internalIp(ip)) {
            return "内网IP";
        }
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("ip", ip);
        try {
            HttpResult httpResult = httpClientService.doPost(IP_URL, hashMap);
            if (httpResult.getCode() != 200) {
                logger.error("获取地理位置异常 {}", ip);
                return address;
            }
            System.out.print("获取到的地址为：" + httpResult.getData());
            JSONObject data = JSONObject.parseObject(httpResult.getData());
            String region = data.getString("region");
            String city = data.getString("city");
            address = region + " " + city;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address;
    }
}
